package com.cms.common;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

public class CmsClassUtils extends ClassUtils{

	/***
	 * 
	 * @param cls
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public static Object instance(String cls) throws InstantiationException, IllegalAccessException, ClassNotFoundException
	{
		return Class.forName(cls).newInstance();
	}
	
	
	/***
	 * 
	 * @param cls
	 * @param fieldName
	 * @return
	 */
	public static Field getField(Class cls,String fieldName)
	{
		try 
		{
			if(StringUtils.isBlank(fieldName))
			{
				return null;
			}
			return cls.getDeclaredField(fieldName);
		} 
		catch (NoSuchFieldException e)
		{
			try {
				return cls.getSuperclass().getDeclaredField(fieldName);
			}   catch (NoSuchFieldException e1) {
				return null;
			}
		}
	}
	
	/***
	 * 
	 * @param cls
	 * @param methodName
	 * @return
	 */
	public static Method getMethodIgnoreParam(Class cls,String methodName)
	{
	      Method[]methods=cls.getMethods();	
	      if(methods!=null&&methods.length!=0)
	      {
	    	   for(Method m:methods)
	    	   {
	    		    if(StringUtils.equals(methodName, m.getName()))
	    		    {
	    		    	return m;
	    		    }
	    	   }
	      }
	      throw new IllegalArgumentException("参数信息异常。无法找到可用【"+methodName+"】调用。");
	}
	
	
	/***
	 * 
	 * @param cls
	 * @param fieldName
	 * @return
	 */
	public static Object getFieldValue(Object target,String fieldName)
	{ 
		Field fl = getField(target.getClass(), fieldName);
		if(fl==null)
		{
			return StringUtils.EMPTY;
		}
		fl.setAccessible(true); 
		try {
			return FieldUtils.readField(fl, target);
		} catch (IllegalAccessException e) {
			 return StringUtils.EMPTY;
		}
	}
	
	
	/**
	 * 判断类是否为基础类型
	 * @param clz
	 * @return
	 */
	public static boolean isBaseDataType(Class clz) {
		return (clz.equals(String.class) || clz.equals(Integer.class)
				|| clz.equals(Byte.class) || clz.equals(Long.class)
				|| clz.equals(Double.class) || clz.equals(Float.class)
				|| clz.equals(Character.class) || clz.equals(Short.class)
				|| clz.equals(BigDecimal.class) || clz.equals(BigInteger.class)
				|| clz.equals(Boolean.class) || clz.equals(Date.class)
				|| clz.isPrimitive());
	}
}
